package nautilus.moneykeeper.net;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class Connection {
	
	private static final String tag = "nautilus.moneykeeper.net.Connection";
	
	public static boolean isNetworkAvailable(Context context){
		ConnectivityManager cmgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] netInfo = cmgr.getAllNetworkInfo();
		
		for(NetworkInfo ni: netInfo){
			if(ni.getTypeName().equalsIgnoreCase("wifi") && ni.isConnected())
				return true;
			
			if(ni.getTypeName().equalsIgnoreCase("mobile") && ni.isConnected())
				return true;
		}
		return false;
	}
	
	public static boolean isServerAvailable(Context context, String strUrl, int timeout){
		final ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo netInfo = cm.getActiveNetworkInfo();
		HttpURLConnection con = null;
		try{
			if(netInfo != null && netInfo.isConnected()){
				URL url = new URL(strUrl);
				con = (HttpURLConnection)url.openConnection();
				con.setConnectTimeout(timeout);
				con.connect();
				con.disconnect();
				return true;
			}
		}catch(MalformedURLException e){
			Log.e(tag, e.getMessage());
		}catch(IOException e2){
			if(con != null) con = null;
			Log.e(tag, e2.getMessage());
		}
		
		return false;
	}
}
